<?php
require_once 'common.inc.php';

$level = pdo_fetchcolumn("select level from".tablename("account_wechats")." where uniacid = '".intval($_W['uniacid'])."' ");
$level = intval($level);

if ($operation == 'display'){
    $modules = pdo_fetch("select mid,settings from ".tablename("modules")." where name = '".MODULE_NAME."' order by mid desc limit 1 ");
    
    if(!empty($modules) && empty($modules['settings'])){
        pdo_update("modules",array('settings'=>1),array('mid'=>$modules['mid']));
    }
    $is_file = is_file(IA_ROOT . "/addons/".MODULE_NAME."/static/fonts/msyh.ttf");
    
    $pindex = max(1, intval($_GPC["page"]));
    $psize = 10;
    $params = array(
        ":uniacid" => $uniacid
    );
    $condition = " and uniacid=:uniacid ";
    if (! empty($_GPC["keyword"])) {
        $_GPC["keyword"] = htmlspecialchars_decode($_GPC["keyword"]);
        $condition .= " AND `title` LIKE :title";
        $params[":title"] = "%" . htmlspecialchars_decode($_GPC["keyword"]) . "%";
    }
    if (! empty($_GPC["type"])) {
        $condition .= " AND `type` = :type";
        $params[":type"] = intval($_GPC["type"]);
    }
    $list = pdo_fetchall("SELECT * FROM " . tablename(MODULE_PREFIX.'poster') . " WHERE 1 {$condition} ORDER BY isdefault desc,createtime desc LIMIT " . ($pindex - 1) * $psize . "," . $psize, $params);
    foreach ($list as &$row) {
        $row["follows"] = pdo_fetchcolumn("select count(*) from " . tablename(MODULE_PREFIX.'log') . " where posterid=:posterid and uniacid=:uniacid", array(
            ":posterid" => $row["id"],
            ":uniacid" => $uniacid
        ));
    }
    unset($row);
    $total = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename(MODULE_PREFIX.'poster') . " where 1 {$condition} ", $params);
    $pager = pagination($total, $pindex, $psize);
}

elseif($operation == 'post'){

    
    $id = intval($_GPC["id"]);
    $item = pdo_fetch("SELECT * FROM " . tablename(MODULE_PREFIX.'poster') . " WHERE id =:id and uniacid=:uniacid limit 1", array(
        ":id" => $id,
        ":uniacid" => $uniacid
    ));

    $item['send_poster'] = unserialize($item['send_poster']);
    $poster_data = json_decode($item['send_poster']['data'],true);

    if (!empty($item)) {
        $data = json_decode(str_replace("&quot;", "'", $item["data"]), true);
    }
    if (checksubmit("submit")) {
        $data = array(
            "uniacid" => $uniacid,
            "title" => htmlspecialchars_decode($_GPC["title"]),
            "type" => intval($_GPC["type"]),
            "keyword" => htmlspecialchars_decode($_GPC["keyword"]),
            "bg" => save_media($_GPC["bg"]),
            "data" => htmlspecialchars_decode($_GPC["data"]),
            "resptitle" => htmlspecialchars_decode($_GPC["resptitle"]),
            "respthumb" => save_media($_GPC["respthumb"]),
            "respdesc" => htmlspecialchars_decode($_GPC["respdesc"]),
            "respurl" => htmlspecialchars_decode($_GPC["respurl"]),
            "createtime" => time(),
            "oktext" => htmlspecialchars_decode($_GPC["oktext"]),
            "waittext" => htmlspecialchars_decode($_GPC["waittext"]),
            "subcredit" => intval($_GPC["subcredit"]),
            "reccredit" => intval($_GPC["reccredit"]),
            "recmoney" => htmlspecialchars_decode($_GPC["recmoney"]),
            "rec_credit_random" => htmlspecialchars_decode($_GPC["rec_credit_random"]),
            "rec_money_random"  => htmlspecialchars_decode($_GPC["rec_money_random"]),
            "submoney" => htmlspecialchars_decode($_GPC["submoney"]),
            "scantext" => htmlspecialchars_decode($_GPC["scantext"]),
            "subtext" => htmlspecialchars_decode($_GPC["subtext"]),
            "bedown" => intval($_GPC["bedown"]),
            "beagent" => intval($_GPC["beagent"]),
            
            "isopen" => intval($_GPC["isopen"]),
            "opentext" => htmlspecialchars_decode($_GPC["opentext"]),
            "openurl" => htmlspecialchars_decode($_GPC["openurl"]),
            
            "paytype" => intval($_GPC["paytype"]),
            "subpaycontent" => htmlspecialchars_decode($_GPC["subpaycontent"]),
            "recpaycontent" => htmlspecialchars_decode($_GPC["recpaycontent"]),
            "templateid" => htmlspecialchars_decode($_GPC["templateid"]),

            "random" => htmlspecialchars_decode($_GPC["random"]),
            "sendtype" => htmlspecialchars_decode($_GPC["sendtype"]),
            "sendval" => htmlspecialchars_decode($_GPC["sendval"]),
            "sendurl" => htmlspecialchars_decode($_GPC["sendurl"]),
            "sendcode" => htmlspecialchars_decode($_GPC["sendcode"]),
            "followcode" => htmlspecialchars_decode($_GPC["followcode"]),
            "pcate" => intval($_GPC['category']["parentid"]),
            "ccate" => intval($_GPC['category']["childid"]),
            
            "isopen_level" => intval($_GPC["isopen_level"]),
            'level_type' => intval($_GPC['level_type']),
            "level1_credit" => htmlspecialchars_decode($_GPC["level1_credit"]),
            "level2_credit" => htmlspecialchars_decode($_GPC["level2_credit"]),
            "level3_credit" => htmlspecialchars_decode($_GPC["level3_credit"]),
            "level1_money" => htmlspecialchars_decode($_GPC["level1_money"]),
            "level2_money" => htmlspecialchars_decode($_GPC["level2_money"]),
            "level3_money" => htmlspecialchars_decode($_GPC["level3_money"]),
            "level0_val" => htmlspecialchars_decode($_GPC["level0_val"]),
            "level0_url" => htmlspecialchars_decode($_GPC["level0_url"]),
            "coverimg" => htmlspecialchars_decode($_GPC["coverimg"]),
            'limitrandom' => intval($_GPC["limitrandom"]),
            'relaystart' => intval($_GPC["relaystart"]),
            
            'isclock'   => intval($_GPC['isclock']),
            'clock_start_time' => htmlspecialchars_decode($_GPC['clock_start_time']),
            'clock_end_time' => htmlspecialchars_decode($_GPC['clock_end_time']),
            'clock_msg' => htmlspecialchars_decode($_GPC['clock_msg']),
            'clock_err' => htmlspecialchars_decode($_GPC['clock_err']),
            'clock_send_credit' => intval($_GPC['clock_send_credit']),
            'clock_send_money'  => floatval($_GPC['clock_send_money']),
            
            'reckeyword'  => trim($_GPC['reckeyword']),
            'reckeyword_prefix'  => trim($_GPC['reckeyword_prefix']),
            'minetext'  => htmlspecialchars_decode($_GPC['minetext']),
            'next_active_text'  => htmlspecialchars_decode($_GPC['next_active_text']),
            'scan_random_text'  => htmlspecialchars_decode($_GPC['scan_random_text']),
            'subresptype'       => intval($_GPC['subresptype']),
            'subresp_keyword'   => htmlspecialchars_decode($_GPC['subresp_keyword']),
            'isopenauto'   => intval($_GPC['isopenauto']),
            'subaudio_url'   => htmlspecialchars_decode($_GPC['subaudio_url']),
            'sub_sendval'   => htmlspecialchars_decode($_GPC['sub_sendval']),
            'sub_sendurl'   => htmlspecialchars_decode($_GPC['sub_sendurl']),
            
            'isunsubscribe'   => intval($_GPC['isunsubscribe']),
            'unsub_sendval'   => htmlspecialchars_decode($_GPC['unsub_sendval']),
            
            'israndomimg'   => intval($_GPC['israndomimg']),
            'randomimgs'    => serialize($_GPC['randomimgs']),

            'ischeckpwd'  => intval($_GPC['ischeckpwd']),
            'password'    => trim($_GPC['password']),
            'pwdinfo'     => trim($_GPC['pwdinfo']),
            'pwdfail'     => trim($_GPC['pwdfail']),

            'is_parent_info'  => intval($_GPC['is_parent_info']),
            'parent_info'    => trim($_GPC['parent_info']),

            'is_groupid'    => trim($_GPC['is_groupid']), // 是否自动打标签分组
            'groupid'    => trim($_GPC['groupid']), // 自动打标签分组
        );

        if(!empty($_GPC['is_parent_info'])){
            if(!pdo_fieldexists(MODULE_PREFIX.'poster','is_parent_info')){
                pdo_query("ALTER TABLE ".tablename(MODULE_PREFIX.'poster')." ADD `is_parent_info`  TINYINT(1) NOT NULL DEFAULT '0' COMMENT '是否开启获取一级用户信息';");
            }
            if(!pdo_fieldexists(MODULE_PREFIX.'poster','parent_info')){
                pdo_query("ALTER TABLE ".tablename(MODULE_PREFIX.'poster')." ADD `parent_info`  VARCHAR(255) NOT NULL DEFAULT '' COMMENT '获取一级用户信息通知';");
            }
            $data['is_parent_info'] = intval($_GPC['is_parent_info']);
            $data['parent_info'] = trim($_GPC['parent_info']);
        }

        // 返回海报
        $poster_data = array(
            'data' => htmlspecialchars_decode($_GPC['poster']['data']),
            'bg' => tomedia($_GPC['poster']['bg']),
            'color' => $_GPC['poster']['color'],
            'img' => tomedia($_GPC['poster']['img']),
        );
        $data['send_poster'] = serialize($poster_data);
        if (! empty($id)) {
            
            // 清除多余海报图片
            load()->func('file');
            rmdirs(IA_ROOT."/addons/".MODULE_NAME."/static/data/" . $_W['uniacid'] . "/".$id."/");

            pdo_update(MODULE_PREFIX.'poster', $data, array( "id" => $id, "uniacid" => $uniacid ));
        } else {
            pdo_insert(MODULE_PREFIX.'poster', $data);
            //pdo_debug();die();
            $id = pdo_insertid();
        }

        if( empty($id) ){
			
            message("添加失败");
        }
        
        $rule = pdo_fetch("select * from " . tablename('rule') . " where uniacid=:uniacid and module=:module and name=:name  limit 1", array(
            ":uniacid" => $uniacid,
            ":module" => MODULE_NAME,
            ":name" => MODULE_NAME
        ));
        
        if (empty($rule)) {
            $rule_data = array(
                "uniacid" => $uniacid,
                "name" => MODULE_NAME,
                "module" => MODULE_NAME,
                "displayorder" => 0,
                "status" => 1
            );
            pdo_insert('rule', $rule_data);
            $rule['id'] = pdo_insertid();
        }
        
        if(!empty($data["keyword"])){
            $rule_keyword = pdo_fetch("select * from " . tablename('rule_keyword') . " where rid=:rid and uniacid=:uniacid and module=:module and content=:content  limit 1", array(
                ":uniacid" => $uniacid,
                ":module" => MODULE_NAME,
                ":content" => htmlspecialchars_decode($data["keyword"]),
                ":rid" => $rule['id'],
            ));
            
            if(!empty($rule_keyword)){
                pdo_update('rule_keyword', array( "content" => htmlspecialchars_decode($data["keyword"]) ), array( "rid" => $rule_keyword["id"] ));
            }else{
                $keyword_data = array(
                    "uniacid" => $uniacid,
                    "rid" => $rule['id'],
                    "module" => MODULE_NAME,
                    "content" => htmlspecialchars_decode($data["keyword"]),
                    "type" => 1,
                    "displayorder" => 0,
                    "status" => 1
                );
                pdo_insert('rule_keyword', $keyword_data);
            }
        }
        
        $ruleauto = pdo_fetch("select * from " . tablename('rule') . " where uniacid=:uniacid and module=:module and name=:name  limit 1", array(
            ":uniacid" => $uniacid,
            ":module" => MODULE_NAME,
            ":name" => MODULE_NAME.":auto"
        ));
        if (empty($ruleauto)) {
            $rule_data = array(
                "uniacid" => $uniacid,
                "name" => MODULE_NAME.":auto",
                "module" => MODULE_NAME,
                "displayorder" => 0,
                "status" => 1
            );
            pdo_insert('rule', $rule_data);
            $rid = pdo_insertid();
            $keyword_data = array(
                "uniacid" => $uniacid,
                "rid" => $rid,
                "module" => MODULE_NAME,
                "content" => strtoupper(MODULE_NAME),
                "type" => 1,
                "displayorder" => 0,
                "status" => 1
            );
            pdo_insert("rule_keyword", $keyword_data);
        }
        
        
        message("更新成功！", $this->createWebUrl("manage", array("op" => "display")), "success");
    }
    
    $imgroot = $_W["attachurl"];
}

elseif($operation == 'delete'){
    $id = intval($_GPC["id"]);
    $poster = pdo_fetch("SELECT id,title,keyword FROM " . tablename(MODULE_PREFIX.'poster') . " WHERE id = '$id'");
    if (empty($poster)) {
        message("抱歉，海报不存在或是已经被删除！", $this->createWebUrl("manage", array( "op" => "display" )), "error");
    }
	load()->func('file');
    rmdirs(IA_ROOT."/addons/".MODULE_NAME."/static/data/" . $_W['uniacid'] . "/" . $id . "/");
    pdo_delete(MODULE_PREFIX.'poster', array( "id" => $id, "uniacid" => $uniacid ));
    pdo_delete(MODULE_PREFIX."log", array( "posterid" => $id, "uniacid" => $uniacid ));
    pdo_delete(MODULE_PREFIX."qr", array( "posterid" => $id, "uniacid" => $uniacid ));
    
    if(!empty($poster['keyword'])){
        pdo_delete("rule_keyword", array( "module" => MODULE_NAME, "content" => $poster['keyword'] ));
        $rid = pdo_fetchcolumn("select rid from ".tablename("rule_keyword")." where module = '".MODULE_NAME."' and content = '".$poster['keyword']."' ");
        if(!empty($rid)){
            pdo_delete("rule", array( "id" =>$rid));
        }
    }
    if(!empty($poster['reckeyword'])){
        pdo_delete("rule_keyword", array( "module" => MODULE_NAME, "content" => $poster['reckeyword'] ));
        $rid = pdo_fetchcolumn("select rid from ".tablename("rule_keyword")." where module = '".MODULE_NAME."' and content = '".$poster['reckeyword']."' ");
        if(!empty($rid)){
            pdo_delete("rule", array( "id" =>$rid));
        }
    }
    
    message("删除成功！", $this->createWebUrl("manage", array( "op" => "display" )), "success");
}
elseif($operation == 'qrdelete'){
    $id = intval($_GPC["id"]);
    $poster = pdo_fetch("SELECT id,title,keyword FROM " . tablename(MODULE_PREFIX.'poster') . " WHERE id = '$id'");
    if (empty($poster)) {
        message("抱歉，海报不存在或是已经被删除！", $this->createWebUrl("manage", array( "op" => "display" )), "error");
    }
	load()->func('file');
    rmdirs(IA_ROOT."/addons/".MODULE_NAME."/static/data/" . $_W['uniacid'] . "/" . $id . "/");
    pdo_delete(MODULE_PREFIX."log", array( "posterid" => $id, "uniacid" => $uniacid ));
    pdo_delete(MODULE_PREFIX."qr", array( "posterid" => $id, "uniacid" => $uniacid ));
    
    message("删除成功！", $this->createWebUrl("manage", array( "op" => "display" )), "success");
}
elseif($operation == 'logdelete'){
    $id = intval($_GPC["id"]);
    pdo_delete(MODULE_PREFIX."log", array( "id" => $id ));
    message("删除成功！", $this->createWebUrl("manage", array( "op" => "log","id" => intval($_GPC["postid"]) )), "success");
}
elseif($operation == 'log'){
    $condition = " log.uniacid = ".$uniacid." and posterid=" . intval($_GPC["id"]);
    if (!empty($_GPC["keyword"])) {
        $_GPC["keyword"] = htmlspecialchars_decode($_GPC["keyword"]);
        $condition .= " AND ( m.nickname LIKE '%".htmlspecialchars_decode($_GPC["keyword"])."%' or m.realname LIKE '%".htmlspecialchars_decode($_GPC["keyword"])."%' or m.mobile LIKE '%".htmlspecialchars_decode($_GPC["keyword"])."%' ) ";
    }
    if (!empty($_GPC["keyword1"])) {
        $_GPC["keyword1"] = htmlspecialchars_decode($_GPC["keyword1"]);
        $condition .= " AND ( m1.nickname LIKE '%".htmlspecialchars_decode($_GPC["keyword1"])."%' or m1.realname LIKE '%".htmlspecialchars_decode($_GPC["keyword1"])."%' or m1.mobile LIKE '%".htmlspecialchars_decode($_GPC["keyword1"])."%' ) ";
    }
    $starttime = strtotime("-1 month");
    $endtime   = time();
    if (!empty($_GPC["time"])) {
        $starttime = strtotime($_GPC["time"]["start"]);
        $endtime   = strtotime($_GPC["time"]["end"]);
        if ($_GPC["searchtime"] == "1") {
            $condition .= " AND log.createtime >= ".intval($starttime)." AND log.createtime <= ".intval($endtime);
        }
    }
    $list  = pdo_fetchall("SELECT log.*, m.avatar,m.nickname,m.realname,m.mobile,m1.avatar as avatar1,m1.nickname as nickname1,m1.realname as realname1,m1.mobile as mobile1 FROM " . tablename(MODULE_PREFIX."log") . " log " . " left join " . tablename('mc_members') . " m1 on m1.uid = log.uid and m1.uniacid = log.uniacid " . " left join " . tablename('mc_members') . " m on m.uid = log.from_uid  and m.uniacid = log.uniacid" . " WHERE {$condition} ORDER BY log.createtime desc " . "  LIMIT " . ($pindex - 1) * $psize . "," . $psize);
    $total = pdo_fetchcolumn("SELECT count(*)  FROM " . tablename(MODULE_PREFIX."log") . " log " . " left join " . tablename('mc_members') . " m1 on m1.uid = log.uid and m1.uniacid = log.uniacid " . " left join " . tablename('mc_members') . " m on m.uid = log.from_uid and m.uniacid = log.uniacid " . " where {$condition}  ");
    foreach ($list as &$row) {
        $row["times"] = pdo_fetchcolumn("select count(*) from " . tablename(MODULE_PREFIX."log") . " where from_uid=:from_uid and posterid=:posterid and uniacid=:uniacid", array(
            ":from_uid" => $row["from_uid"],
            ":posterid" => intval($_GPC["id"]),
            ":uniacid" => $uniacid
        ));
    }
    unset($row);
    $pager = pagination($total, $pindex, $psize);
}

elseif($operation == 'updateMember'){
    $updateMember = cache_load($key);
    if(empty($updateMember)){
        pdo_query("alter table ".tablename("mc_members")." modify column nickname varbinary(100);");
        cache_write("updateMember", 1);
        message("系统会员表字段修复成功！",referer(),"success");
    }else{
        message("请勿重复提交！",referer(),"error");
    }
}

// 清除所有测试数据
elseif ($operation == 'deleteall'){
    // 清除多余海报图片
    load()->func('file');
    rmdirs(IA_ROOT."/addons/".MODULE_NAME."/static/data/" . $_W['uniacid'] . "/");

    //pdo_delete(MODULE_PREFIX."log",array('uniacid'=>$uniacid));
	//pdo_update(MODULE_PREFIX."member",array('scancodenum'=>0,'randomnum'=>0,'level'=>0,'level1_uid'=>0,'level2_uid'=>0,'level3_uid'=>0),array('uniacid'=>$uniacid));
	pdo_delete(MODULE_PREFIX."qr",array('uniacid'=>$uniacid));
	//pdo_update(MODULE_PREFIX."qr",array('nums'=>0,'randomnum'=>0,'updatenum'=>0,'finish_random_nums'=>0),array('uniacid'=>$uniacid));
	
	message("数据清理成功！",referer(),"info");
}
include $this->template('web/manage');